package br.com.firula.web.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LanguageFilter implements Filter {
    
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain)
    throws IOException, ServletException {
    	HttpServletRequest request = (HttpServletRequest)req;
    	HttpServletResponse response = (HttpServletResponse)res;
    	HttpSession session = request.getSession();
    	final String paramName = "request_locale";
    	String param = request.getParameter(paramName);
        String idioma = (String)session.getAttribute("LANG");
        if(param == null || param.equals("") || param.equals("pt")){
        	session.removeAttribute("LANG");
    		session.setAttribute("catalogo",false);
    		session.setAttribute("img_prefix", "");
    		session.setAttribute("WW_TRANS_I18N_LOCALE", new Locale("pt"));
    	}else{
        	session.setAttribute("LANG", param);
        	session.setAttribute("catalogo", true);
        	session.setAttribute("img_prefix", param+"_");
        	session.setAttribute("WW_TRANS_I18N_LOCALE", new Locale(param));
        } 
                	
    	if((param == null || param.equals("")) && idioma != null && session.getAttribute("ADMINISTRADOR")== null){
        	String redir = request.getContextPath()+ request.getServletPath()+"?"+(request.getQueryString() == null ? "" : request.getQueryString().replace(paramName+"=","")+"&")+paramName+"="+idioma;
        	response.sendRedirect(redir);
        	return;
        }
        chain.doFilter(req, res);
        
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}
